<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage Commercial core plugins
 */


/**
 * Smarty phone_format modifier plugin
 *
 * Type:     modifier<br>
 * Name:     phone_format<br>
 * Date:     Oct 20, 2008
 * Purpose:  unified formatting for phones
 * Input:    string
 * Example:  {$item.phone|phone_format}
 *           {'+7(095)1231231'|phone_format} -> "<small>+7 495</small> 123 1231"
 *           {'+7(095)1231231'|phone_format:1} -> "+7 495 123 1231"
 *           {'+7926 1231231'|phone_format} -> "+7 926 123 1231"
 * @author   Alex Yaroshevich <qfox@ya.ru>
 * @version 0.1
 * @param string with phone
 * @return string
 */
function smarty_modifier_phone_format( $phone, $beauty = 1 )
{
	$plusexist = ( strpos( $phone, '+' ) !== 0 );
	// old moscow numbers
	//$phone = preg_replace( array( '(095)', ' 095 ', '+7095' ), array( '495', '495', '+7495' ), $phone );
	$_p = preg_replace( '/[^0-9#]/', '', $phone );
	$_p = preg_replace( '/^789/', '79', $_p );
	list( $_p, $_p2 ) = explode( '#', $_p.'#' );
	
	// evaluation
	$_r = "";
	switch( strlen( $_p ) )
	{
	case 7:
		$_r = "+7 495 ".substr( $_p, 0, 3 )." ".substr( $_p, 3 );
		break;
	case 11:
		$_r = ( $_p{0} == 7 || $_p{0} == 8 ) ? "+7 " : '+'.$_p{0}.' ';
		switch( $_p[1].$_p[2] )
		{
		case 81: case 49:
		case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: case 98:
		$_r .= substr( $_p, 1, 3 ).' ';
		$_r .= substr( $_p, 4, 3 ).'-';
		$_r .= substr( $_p, 7 );
		break;
		default:
		$_r .= sprintf( '<a href="http://mtt.ru/info/codes/index.wbp?countryCode=%2$d&cityCode=%1$d" target="_blank">%1$d</a>-', substr( $_p, 1, 3 ), $_p[ 0 ] );
		$_r .= substr( $_p, 4, 1 ).' ';
		$_r .= substr( $_p, 5, 3 ).'-';
		$_r .= substr( $_p, 8 );
		break;
		}
		break;
	default:
	if( strlen( $_p ) < 7 ) {
		$_r = '? '.number_format( $_p, 0, ' ', ' ' );
	} elseif( strlen( $_p ) > 7 && strlen( $_p ) < 10 ) {
		$_r = "? ".substr( $_p, 0, 3 )." ".substr( $_p, 3 );
	} elseif( strlen( $_p ) > 10 ) {
		$_r .= substr( $_p, 1, 3 ).' ';
		$_r .= substr( $_p, 4, 3 ).' ';
		$_r .= substr( $_p, 7 );
		$_r = "$ ".substr( $_p, 1, 3 )." ".substr( $_p, 3 );
	}
	}
	
	if( $_p2 )
		$_r .= ', доб. '.$_p2;
	
	if( $beauty )
	{
		$_r = preg_replace( '/^\+7 49/', "<small>+7 49</small>", 
			preg_replace( '/^\+7 495 /', "<small>+7 495</small> ", 
			preg_replace( '/^\+7 812 /', "<small>+7 812</small> ", 
			$_r ) ) );
	}
	
	return $_r;
}

/* vim: set expandtab: */

?>
